package th.co.exat.util;

import java.io.File;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class SAXWithJdom {

    public static void main(String[] args) throws Exception {
        /*
        String xml = "<Payments><customer id='1'><item>1001</item>"
        + "<price>1000.00</price></customer><customer id='2'>"
        + "<item>1002</item><price>20.00</price></customer></Payments>";
        try {
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = (Document) saxBuilder.build(new ByteArrayInputStream(xml.getBytes("UTF-8")));

        //Get root element [Payments]
        Element rootElement = document.getRootElement();

        //Get all child with tag [customer]
        List<Element> elements = rootElement.getChildren("customer");
        for (Element el : elements) {
        System.out.println("Customer Id : " + el.getAttributeValue("id"));
        System.out.println("item : " + el.getChildTextTrim("item"));
        System.out.println("price : " + el.getChildTextTrim("price") + "\n");
        }
        } catch (IOException ex) {
        ex.printStackTrace();
        } catch (JDOMException ex) {
        ex.printStackTrace();
        } catch (Exception ex) {
        ex.printStackTrace();
        }
         * 
         */
        String xml = "<Payments><customer id='1'><item>1001</item>"
                + "<price>1000.00</price></customer><customer id='2'>"
                + "<item>1002</item><price>20.00</price></customer></Payments>";
        String path = new java.io.File(".").getCanonicalPath();
        System.out.println(path);
        List<Element> elements = parserXML(path + "/build/web/Province.xml", "Province");
        for (Element el : elements) {
            System.out.println("price : " + el.getChildTextTrim("ProvinceName") + "\n");
        }
    }

    public static List<Element> parserXML(String xmlFile, String subElement) throws Exception {

        SAXBuilder saxBuilder = new SAXBuilder();
        File xml = new File(xmlFile);

        //Document document = (Document) saxBuilder.build(new ByteArrayInputStream(xml.getBytes("UTF-8")));
        Document document = (Document) saxBuilder.build(xml);
        //Get root element [Payments]
        Element rootElement = document.getRootElement();

        //Get all child with tag [customer]
        List<Element> elements = rootElement.getChildren(subElement);

        return elements;
    }

}
